﻿<?
class FNC {
	function FNC(){
		
	}
	function fnStrConvert($text){
	
	   # Convert values from Lower to Upper
	   $arrayLower=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','à','á','ả','ã','ạ','ă','ằ','ắ','ẳ','ẵ','ặ','â','ầ','ấ','ẩ','ẫ','ậ','đ','è','é','ẻ','ẽ','ẹ','ê','ề','ế','ể','ễ','ệ','ì','í','ỉ','ĩ','ị','ò','ó','ỏ','õ','ọ','ô','ồ','ố','ổ','ỗ','ộ','ơ','ờ','ớ','ở','ỡ','ợ','ù','ú','ủ','ũ','ụ','ư','ừ','ứ','ử','ữ','ự','ỳ','ý','ỷ','ỹ','ỵ','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','À','Á','Ả','Ã','Ạ','Ă','Ằ','Ắ','Ẳ','Ẵ','Ặ','Â','Ầ','Ấ','Ẩ','Ẫ','Ậ','Đ','È','É','Ẻ','Ẽ','Ẹ','Ê','Ề','Ế','Ể','Ễ','Ệ','Ì','Í','Ỉ','Ĩ','Ị','Ò','Ó','Ỏ','Õ','Ọ','Ô','Ồ','Ố','Ổ','Ỗ','Ộ','Ơ','Ờ','Ớ','Ở','Ỡ','Ợ','Ù','Ú','Ủ','Ũ','Ụ','Ư','Ừ','Ứ','Ử','Ữ','Ự','Ỳ','Ý','Ỷ','Ỹ','Ỵ');
	   $arrayUpper=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','d','e','e','e','e','Ẹ','e','e','e','e','e','e','i','i','i','i','i','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','u','u','u','u','u','u','u','u','u','u','u','y','y','y','y','y','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','D','E','E','E','E','Ẹ','E','E','E','E','E','E','I','I','I','I','I','O','O','O','O','O','O','O','O','O','O','O','O','O','O','O','O','O','U','U','U','U','U','U','U','U','U','U','U','Y','Y','Y','Y','Y');
	
	if($text == ''){
	   return $text;
	}
	
	   $text=str_replace($arrayLower, $arrayUpper, $text);
	   return($text);
	} #end of function	
	
	function vndate2date($date,$sp='/'){
		if ($date!='')
		{
			$tmp = explode($sp,$date);
			$strdate = $tmp[2].'/'.$tmp[1].'/'.$tmp[0];
			return $strdate;			
		}else{
			return true;
		}
	}
	
	function vndatetime2date($date,$sp='/'){
		
		
		if ($date!='')
		{
			$dt_arr = explode(' ',$date);			
			$tmp = explode($sp,$dt_arr[0]);
			$strdate = $tmp[2].'/'.$tmp[1].'/'.$tmp[0].' '.$dt_arr[1];
			return $strdate;			
		}else{
			return true;
		}
	}	
	
	function date2vndate($date,$time=true){
		if ($date!=''){
			$tmp = strtotime($date);
			$strdate = date('d/m/Y',$tmp);
			$strtime = ' '.date('H:i:s',$tmp);
			if ($time){
				return $strdate.$strtime;
			}else
			{
				return $strdate;	
			}
		}else{
			return '';
		}
		
		
	}	
	
	function dateadd($v,$d=null , $f="m/d/Y"){ 
	  $d=($d?$d:date("Y-m-d")); 
	  return date($f,strtotime($v." days",strtotime($d))); 
	}


	function date_diff($start, $end)
	{
	   	$dateDiff = strtotime($end) - strtotime($start);
		$fullDays = ($dateDiff/(60*60*24));  		
		return $fullDays;   
	}



	function nb_format($digits,$number=0){
		return number_format($digits, $number, '.', ',');
	}

	function nb_format2($digits,$number=0){
		return number_format($digits, $number, ',', '.');
	}

	function iif($expression, $returntrue, $returnfalse = ''){
		return ($expression ? $returntrue : $returnfalse);
	}

	function isNull($vl,$def){
		if (empty($vl) || $vl==null){return $def;}
		else 
			return $vl;
	}
	
	function randomString($length = 8)
    {
        $str = '';
        $allowed_chars = '2346789ABCDEFGHJKLMNPRTWXYZ';
        $chars_length = strlen($allowed_chars) - 1;

        for ($i = 0; $i < $length; $i++) {
            $str .= $allowed_chars{rand(0, $chars_length)};
        }

        return $str;
    }

	function getform()
	{
		 $array=($_POST);   	 
		 $key_arrays=array_keys($array);    
	 
		 for ($i=0;$i<count($key_arrays);$i++)
		 {	 	
			print "$".$key_arrays[$i]."=$"."_POST[".chr(34).$key_arrays[$i].chr(34)."];<br>";
		 }

		 $array=($_GET);   	 
		 $key_arrays=array_keys($array);    
	 
		 for ($i=0;$i<count($key_arrays);$i++)
		 {	 	
			print "$".$key_arrays[$i]."=$"."_GET[".chr(34).$key_arrays[$i].chr(34)."];<br>";
		 }

	}	
	
	function ExportToExcel($filename='',$exportStr='') {
		$Date		= time();
		$exportContent =  	"<html>
							<head>
							<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> 							
							</head>
							<body>
								$exportStr
							</body>
							</html>";
		header('HTTP/1.1 200 OK');
		header('Cache-Control: public, must-revalidate');
		header('Expires: '.gmdate('D, d M Y H:i:s', $Date).' GMT');
		header('Date: ' . date("D M j G:i:s T Y", $Date));
		header('Last-Modified: ' . date("D M j G:i:s T Y", $Date));
		header('Content-type: applicationnd.ms-excel;charset=utf-8');
		header("Content-Transfer-Encoding: binary");
		header('Content-type:charset=utf-8');
		header('Content-Disposition: attachment; filename="'.$filename.'.xls"'); 
		print $exportContent;
		exit;
	}	
	
	function _fnSortOrderBy(){
		$tmp='
					<input type="hidden" name="_SortOrderBy" id="_SortOrderBy"  value="'.$_POST['_SortOrderBy'].'">
					<input type="hidden" name="_OrderDirection" id="_OrderDirection"  value="'.$_POST['_OrderDirection'].'">
					<script>
					function fnOrder(_col){
						var frm = document.form1;	
						var _ord = $("#_SortOrderBy");
						var _orddir = $("#_OrderDirection");
						if (_ord.val()==""){_ord.val(_col);	_orddir.val("asc")}
						if (_ord.val()==_col){
							if (_orddir.val()=="asc")
								{_orddir.val("desc")}
							else
							 	{ _orddir.val("asc")}
						}
						if (_ord.val()!=_col){
							_ord.val(_col)
							_orddir.val("asc")
						}
						frm.submit();						
					}
					
					
					</script>'	;		
		
		return $tmp;
	}
	
	function setPaging(){
		if ($this->TotalPage>0)
		{	
			$_Paging='<table width=100% cellpadding=0 cellspacing=0><tr><td colspan=100 align=left>'.$this->Paging($this->TotalPage,$this->PageIndex,'form1').'</td></tr></table>';
		}
		return $_Paging;
	}

	function setFooter(){$_Footer='</table></div></div>';return $_Footer;}		
	
	function PageHeader(){	
		$PageArr = array('2','5','10','20','50','100');
		$_PageHeader='
				<table width="100%">
				    <tr>
				         <td align=left>Tổng số dòng : <b style="color:red">'.$this->TotalRecord.'</b> / '.$this->TotalPage.' trang</td>
				         <td align="right">Số dòng / trang 
						 	<select name="ddlPageSize" id="ddlPageSize"  onchange="document.form1.submit()" >';
		for ($i=0;$i<count($PageArr);$i++){
		$slted='';
		if 	($PageArr[$i]==$_POST['ddlPageSize'])
		{
			$slted=' selected ';
		}
		
		$_PageHeader.='<option value="'.$PageArr[$i].'" '.$slted.'>'.$PageArr[$i].'</option>';
		}
		
		$_PageHeader.='	</select>
				         </td>
				    </tr>
				</table>';				
		$_PageHeader.=$this->_fnSortOrderBy();				
		return 	$_PageHeader;	
	}	
	
	function Paging($totalPages=0,$currentPage=0,$formName='')
	{
		global $vportal;
		$form = ($formName!=""&&$formName!=null) ? $formName : "forms[0]";
		$strPaging = '<div id="paging" align=center><table border=0 cellpadding=0 cellspacing=0><tr>';
/*			
			/<td><div class="page">ddd</div></td>
			<td><div class="page">ddd</div></td>*/
			
			
			
			

		
		$pSegment = 5;
		if (is_numeric($totalPages))
		{
			$totalSegment = ceil($totalPages/$pSegment);
			$currentSegment = ceil($currentPage/$pSegment);
			$startPage = (($currentSegment-1)*$pSegment) + 1;
			$endPage = $currentSegment * $pSegment;
			$maxPage = ($endPage>$totalPages) ? $totalPages : $endPage;
			if ($currentPage>1)
				$strPaging .= "<td><div class='page'><a href=\"#Trang đầu\" onclick=\"document.$form.page.value='1';document.$form.submit();\"><img src=\"/images/first.png\" border=0 title='First'></a></div></td>";
			//else
			//	$strPaging .= "<img src=\"".$vportal->vars["site_url"]."/images/first_gr.png\"> ";
			if ($currentSegment>1)
				$strPaging .= "<td><div class='page'><a href=\"#Trang trước\" onclick=\"document.$form.page.value='".($currentSegment-1)*$pSegment."';document.$form.submit();\"><img src=\"/images/prevjump.png\" border=0  title='Prev'></a></div></td>";
			//else
			//	$strPaging .= "<img src=\"".$vportal->vars["site_url"]."/images/prevjump_gr.png\"> ";
			if ($currentPage>1)
				$strPaging .= "<td><div class='page'><a href=\"#Trang trước\" onclick=\"document.$form.page.value='".($currentPage-1)."';document.$form.submit();\"><img src=\"/images/prev.png\" border=0  title='Prev'></a></div></td>";
			//else
			//	$strPaging .= "<img src=\"".$vportal->vars["site_url"]."/images/prev_gr.png\"> ";
			
			for ($i=$startPage;$i<=$maxPage;$i++)
			{
				if ($currentPage==$i)
					$strPaging .= '<td><div ><input type="text" class="pgCurrent" value="'.$i.'" alt="integer" id="iCurrentPage" name="iCurrentPage"></div></td>';
				else
					$strPaging .= '<td><div class="page"><a href="#Trang '.$i.'"  onclick="document.'.$form.'.page.value=\''.$i.'\';document.'.$form.'.submit();" 	>'.$i.'</a></div></td>';
			}
			
			if ($currentPage<$totalPages)
				$strPaging .= "<td><div class='page'><a href=\"#Trang trước\" style=\"text-decoration:none\" onclick=\"document.$form.page.value='".($currentPage+1)."';document.$form.submit();\"><img src=\"/images/next.png\" border=0 title='Next'></a></div></td>";
			//else
			//	$strPaging .= "<img src=\"".$vportal->vars["site_url"]."/images/next_gr.png\"> ";
			if ($currentSegment<$totalSegment)
				$strPaging .= "<td><div class='page'><a href=\"#Trang sau\"  style=\"text-decoration:none\"  onclick=\"document.$form.page.value='".($currentSegment*$pSegment+1)."';document.$form.submit();\"><img src=\"/images/nextjump.png\" border=0  title='Next'></a></div></td>";
			//else
			//	$strPaging .= "<li class='pgNext pgEmpty'>kế</li> ";
			if ($currentPage<$totalPages)
				$strPaging .= "<td><div class='page'><a href=\"#Trang cuối\" style=\"text-decoration:none\" onclick=\"document.$form.page.value='".$totalPages."';document.$form.submit();\"><img src=\"/images/last.png\" border=0  title='Last'></a></div></td>";
			//else
			//	$strPaging .= "<img src=\"".$vportal->vars["site_url"]."/images/last_gr.png\"> ";
		}
		
		
		
		$strPaging .= "<td><div class='page'><a href=\"#Trang cuối\" style=\"text-decoration:none\" onclick=\" if (document.$form.iCurrentPage.value==''){document.$form.iCurrentPage.value=1;};document.$form.page.value=document.$form.iCurrentPage.value;  document.$form.submit();\"><b>go to page</b></a></div></td></tr></table></div>";		
		
		
		return $strPaging;
	}






	
	
//==HTML Form====================================================//	
   
    public function startForm($action = '#', $method = 'post', $id = NULL, $attr_ar = array() ) { 
        $str = "<form action=\"$action\" method=\"$method\""; 
        if ( isset($id) ) { 
            $str .= " id=\"$id\" name=\"$id\"  "; 
        } 
        $str .= $attr_ar? $this->addAttributes( $attr_ar ) . '>': '>'; 
        return $str; 
    } 
     
    private function addAttributes( $attr_ar ) { 
        $str = ''; 
        // check minimized attributes 
        $min_atts = array('checked', 'disabled', 'readonly', 'multiple'); 
		$tmp='';
        foreach( $attr_ar as $key=>$val ) { 
			if ($key=='defined')
				$tmp =$val;
			else
			{		
			    if ( in_array($key, $min_atts) ) { 
	                if ( !empty($val) && $key!='defined' ) {  
	                    $str .= " $key=\"$key\""; 
	                } 
	            } else { 
					$str .= " $key=\"$val\""; 	
		        } 
			}
        } 
        return $str.$tmp; 
    } 
     
    public function addInput($type, $name, $value, $attr_ar = array(),$OBJ) { 

		if (trim($value)=='')
		{
			$value = $_POST[$name];
		}	
		
	
        $str = "<input type=\"$type\" name=\"$name\" id=\"$name\" value=\"$value\""; 
        if ($attr_ar) { 
            $str .= $this->addAttributes( $attr_ar ); 
        } 
        $str .= ' />'; 
		$OBJ->assign('_'.$name,$str);
        return $str; 
    } 
  
    public function addInput2($type, $name, $value, $attr_ar = array(),$OBJ,$df_val) { 

		if (trim($value)=='')
		{
			$value = $_POST[$name];
		}	
		if ($df_val!='') {$value = $df_val;}
		
        $str = "<input type=\"$type\" name=\"$name\" id=\"$name\" value=\"$value\""; 
        if ($attr_ar) { 
            $str .= $this->addAttributes( $attr_ar ); 
        } 
        $str .= ' />'; 
		$OBJ->assign('_'.$name,$str);
        return $str; 
    }   
     
    public function addTextarea($name, $rows = 4, $cols = 30, $value = '', $attr_ar = array(),$OBJ ) { 
        $str = "<textarea name=\"$name\" rows=\"$rows\" cols=\"$cols\""; 
        if ($attr_ar) { 
            $str .= $this->addAttributes( $attr_ar ); 
        } 
        $str .= ">$value</textarea>"; 
		$OBJ->assign('_'.$name,$str);
        return $str; 
    } 
     
    // for attribute refers to id of associated form element 
    public function addLabelFor($forID, $text, $attr_ar = array() ) { 
        $str = "<label for=\"$forID\""; 
        if ($attr_ar) { 
            $str .= $this->addAttributes( $attr_ar ); 
        } 
        $str .= ">$text</label>"; 
        return $str; 
    } 
     
    // from parallel arrays for option values and text 
    public function addSelectListArrays($name, $val_list, $txt_list, $selected_value = NULL, $header = NULL, $attr_ar = array() ) { 
        $option_list = array_combine( $val_list, $txt_list ); 
        $str = $this->addSelectList($name, $option_list, true, $selected_value, $header, $attr_ar ); 
        return $str; 
    } 
     
    // option values and text come from one array (can be assoc) 
    // $bVal false if text serves as value (no value attr) 
    public function addSelectList($name, $option_list,  $header = NULL, $attr_ar = array(),$OBJ) { 
        $str = "<select name=\"$name\" id=\"$name\" "; 
        if ($attr_ar) { 
            $str .= $this->addAttributes( $attr_ar ); 
        } 
        $str .= ">\n"; 
        if ( isset($header) ) { 
            $str .= "  <option value=\"\">$header</option>\n"; 
        } 
        foreach ( $option_list as $val => $text ) { 
            $str .= "<option value=\"$val\""; 
            if ( isset($_POST[$name]) && ( trim($_POST[$name]) === trim($val) || trim($_POST[$name]) === trim($text)) ) { 
                $str .= ' selected="selected"'; 
            } 
            $str .= ">$text</option>\n"; 
        } 
        $str .= "</select>"; 
		$OBJ->assign('_'.$name,$str);
        return $str; 
    } 
     
	 
    // option values and text come from one array (can be assoc) 
    // $bVal false if text serves as value (no value attr) 
	
	
    public function addSelectList2($name, $option_list,  $header = NULL, $attr_ar = array(),$OBJ,$vl_selected) { 
		$str = $$name."<select name=\"$name\" id=\"$name\" "; 
        if ($attr_ar) { 
            $str .= $this->addAttributes( $attr_ar ); 
        } 
        $str .= ">\n"; 
        if ( isset($header) ) { 
            $str .= "  <option value=\"\">$header</option>\n"; 
        } 
		
        foreach ( $option_list as $val => $text ) { 
            $str .= "<option value=\"$val\""; 
            if ( isset($_POST[$name]) && ( trim($_POST[$name]) === trim($val) || trim($_POST[$name]) === trim($text)) || trim($vl_selected)===trim($val) ) { 
                $str .= ' selected="selected"'; 
            } 
            $str .= ">$text</option>\n"; 
        } 
        $str .= "</select>"; 
		$OBJ->assign('_'.$name,$str);
        return $str;
    } 	 

    
    public function addSelectList3($name, $option_list,  $header = NULL, $attr_ar = array(),$OBJ,$vl_selected,$size=5) { 
		$vl_selected_arr = explode(",",$vl_selected);
		foreach($vl_selected_arr as $k=>$vl){
			$sl_arr[$vl] = $vl;
		}
		
		$str = $$name."<select name=\"$name\" id=\"$name\" multiple SIZE=\"$size\" "; 
        if ($attr_ar) { 
            $str .= $this->addAttributes( $attr_ar ); 
        } 
        $str .= ">\n"; 
        if ( isset($header) ) { 
            $str .= "  <option value=\"\">$header</option>\n"; 
        } 
		
        foreach ( $option_list as $val => $text ) { 
            $str .= "<option value=\"$val\""; 
			
			if (array_key_exists($val, $sl_arr)){
				 $str .= ' selected="selected"'; 
			}
			
           // if ( isset($_POST[$name]) && ( trim($_POST[$name]) === trim($val) || trim($_POST[$name]) === trim($text)) || trim($vl_selected)===trim($val) ) { 
               
           // } 
            $str .= ">$text</option>\n"; 
        } 
        $str .= "</select>"; 
		$OBJ->assign('_'.$name,$str);
        return $str; 
    }    

     function addSelectList4($name, $option_list,  $header = NULL, $attr_ar = array(),$OBJ,$slted = NULL) { 
        $str = "<select name=\"$name\" id=\"$name\" "; 
        if ($attr_ar) { 
            $str .= $this->addAttributes( $attr_ar ); 
        } 
        $str .= ">\n"; 
        if ( isset($header) ) { 
            $str .= "  <option value=\"\" item0=".$this->md5sum2('@all')." rel=\"-1000\">$header</option>\n"; 
        } 
        foreach ( $option_list as $val => $text ) { 
            $str .= "<option value=\"$val\"  "; 
            if ( isset($_POST[$name]) && ( trim($_POST[$name]) === trim($val) || trim($_POST[$name]) === trim($text) ) || trim($slted) === trim($val) ) { 
                $str .= ' selected '; 
            } 
			
			foreach($text[1] as $keyext => $valext){			
					$str .= ' item'.$keyext.' = "'.$valext.'" '; 
			}
			
            $str .= " rel=\"$val\">".$text[0]."</option>\n"; 
        } 
        $str .= "</select>"; 
		$OBJ->assign('_'.$name,$str);
        return $str; 
    }

    
    public function endForm() { 
        return "</form>"; 
    } 
     
//==END HTML Form====================================================//

	function md5sum($str){
		$code='FNC'.session_id();
		return md5($code.$str.$code);
	}

	function md5sum2($str){
		$code='FNC'.$_SESSION['ws_login_user'];
		return md5($code.$str.$code);
	}	

	function md5check($id){

		$chksum = _get('chksum');
		$token = _get('token');



		if (($chksum!='' && $this->md5sum($id)==$chksum) || ($token!='' && $this->md5sum($id)==$token)){
			$flag=true;
		}else
			{
				$flag=false;				
				die('<div style="color:red">You do not have access to this area. Contact your site administrator to obtain access.</div>');	
			}
		return $flag;	

	}

	function md5check2($txt,$sumVar){		
		
		$sum = _get($sumVar);
		$chksum = _get('chksum');
		$token = _get('token');

		$sum = $sum!=''?$sum:($token!=''?$token:$chksum);

		if (($sum!='' && $this->md5sum2($txt)==$sum) || ($sum!='' && $this->md5sum($txt)==$sum)){
			$flag=true;
		}else
			{
				$flag=false;	
			}
		return $flag;		
	}
//========================================================================//
}	

function _get($id,$def=''){
	$vl = $_POST[$id]!=''?$_POST[$id]:$_GET[$id];
	if (!isset($id) || $id=='' )
		$vl = $def;
	return $vl;	
}
?>